'use client'

import { useEffect, useState } from 'react'
import { Role } from '@prisma/client'
import { RoleForm } from '@/components/roles/role-form'

export default function RolesPage() {
  const [roles, setRoles] = useState<Role[]>([])
  const [editingRole, setEditingRole] = useState<Role | null>(null)

  useEffect(() => {
    async function fetchRoles() {
      try {
        const response = await fetch('/api/roles')
        if (!response.ok) {
          throw new Error('网络错误')
        }
        const data = await response.json()
        if (Array.isArray(data)) {
          setRoles(data)
        } else {
          console.error('返回的数据不是数组:', data)
        }
      } catch (error) {
        console.error('获取角色数据失败:', error)
      }
    }
    fetchRoles()
  }, [])

  const handleEdit = (role: Role) => {
    setEditingRole(role)
  }

  const handleDelete = async (id: number) => {
    const response = await fetch(`/api/roles/${id}`, { method: 'DELETE' })
    if (response.ok) {
      setRoles(roles.filter(role => role.id !== id))
    } else {
      console.error('删除角色失败')
    }
  }

  const handleSave = (updatedRoles: Role[]) => {
    setRoles(updatedRoles)
  }

  return (
    <div className="space-y-4 p-8 bg-gray-50">
      <h1 className="text-2xl font-bold text-gray-800">角色管理</h1>
      <RoleForm role={editingRole} onClose={() => setEditingRole(null)} onSave={handleSave} />
      <table className="min-w-full mt-4 border-collapse border border-gray-300">
        <thead>
          <tr>
            <th className="border border-gray-300 p-2 text-left text-gray-800">角色名称</th>
            <th className="border border-gray-300 p-2 text-left text-gray-800">操作</th>
          </tr>
        </thead>
        <tbody>
          {roles.map(role => (
            <tr key={role.id} className="hover:bg-gray-100">
              <td className="border border-gray-300 p-2 text-gray-800">{role.name}</td>
              <td className="border border-gray-300 p-2">
                <button onClick={() => handleEdit(role)} className="text-blue-600 hover:underline">编辑</button>
                <button onClick={() => handleDelete(role.id)} className="text-red-600 hover:underline ml-2">删除</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}